package com.happyfamily.springboot.crowdsourcingplatform.dto;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.happyfamily.springboot.crowdsourcingplatform.model.SysPermission;
import com.happyfamily.springboot.crowdsourcingplatform.model.SysUser;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Administrator
 * @create 2020/02/20 18:52
 */
@EqualsAndHashCode(callSuper = true)
@Data
public  class LoginBackUser extends SysUser implements UserDetails
{


	private static final long serialVersionUID = -575147173552055957L;
	private List<SysPermission> permissions;

	private String token;
	/**
	 * 登陆时间戳（毫秒）
	 */
	private Long loginTime;
	/**
	 * 过期时间戳
	 */
	private Long expireTime;


	/**
	 * 认证的权限
	 * @return
	 */
	@Override
	@JsonIgnore
	public Collection<? extends GrantedAuthority> getAuthorities()
	{
		//用流的方式来处理如果permissions不为空
		return permissions.parallelStream().filter(p -> !StringUtils.isEmpty(p.getPermission()))
				//封装一个map
				.map(p -> new SimpleGrantedAuthority(p.getPermission()))
				.collect(Collectors.toSet());
	}

	@Override
	@JsonIgnore
	public String getPassword()
	{
		return super.getUpassword();
	}

	@Override
	@JsonIgnore
	public String getUsername()
	{
		return super.getUaccount();
	}


	public void setAuthorities(Collection<? extends GrantedAuthority> authorities)
	{
		// do nothing
	}

	/**
	 *账户是否过期
	 * @return
	 */
	@JsonIgnore
	@Override
	public boolean isAccountNonExpired()
	{
		return true;
	}

	/**
	 * 账户是否被锁定
	 * @return
	 */
	@JsonIgnore
	@Override
	public boolean isAccountNonLocked()
	{
		return getPid() != Status.LOCKED;
	}

	/**
	 * 密码是否未过期
	 * @return
	 */
	@JsonIgnore
	@Override
	public boolean isCredentialsNonExpired()
	{
		return true;
	}

	/**
	 * 账户是否激活
	 * @return
	 */
	@JsonIgnore
	@Override
	public boolean isEnabled()
	{
		//可以判断值是否为1
		return true;
	}

	public Long getLoginTime()
	{
		return loginTime;
	}

	public void setLoginTime(Long loginTime)
	{
		this.loginTime = loginTime;
	}

	public Long getExpireTime()
	{
		return expireTime;
	}

	public void setExpireTime(Long expireTime)
	{
		this.expireTime = expireTime;
	}

}